/**
 * create by Alec
 */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import autobind from "autobind-decorator";
import { RefreshControl, ListView, List, Icon } from "@ali/ding-ui";
import { mid2Url } from "@ali/ding-mediaid";

// components
import DDAvatar from "../../components/Avatar/";

// submodule
import "./index.less";

// actions
import {
    fetchPersonnelEntry,
    fetchPersonnelDimission,
    fetchPersonnelTransferIn,
    fetchPersonnelTransferOut,
    fetchPersonnelTotalTransfer,
    fetchPersonnelTotalBeRegular,
    fetchPersonnelEntryByType,
    fetchPersonnelEntryByStatus
} from "../../actions/statisticList/index.js";

// modules

// utils
import monitor from '../../utils/monitor.js';
import { setTitle, goBack, openLink } from '../../utils/dingtalk.js'

// actions

const mapper = {
    entry: '入职',
    dimission: '离职',
    transferIn: '转入',
    transferOut: '转出',
    totalTransfer: '调岗',
    totalBeRegular: '转正',
}
const typeMapper = {
    '1': '全职',
    '2': '兼职',
    '3': '实习',
    '9': '其他',
}
const statusMapper = {
    '3': '正式',
    '2': '试用期',
    '5': '待离职'
}
const PAGE_SIZE = 15;

const Item = List.Item;

// 将store注入组件的props
const mapStateToProps = state => ({});
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
    //区分绑定到props的action与传递的props
    actions: bindActionCreators(
        {
            dispatch,
            entry: fetchPersonnelEntry,
            dimission: fetchPersonnelDimission,
            transferIn: fetchPersonnelTransferIn,
            transferOut: fetchPersonnelTransferOut,
            totalTransfer: fetchPersonnelTotalTransfer,
            totalBeRegular: fetchPersonnelTotalBeRegular,
            entryByType: fetchPersonnelEntryByType,
            entryByStatus: fetchPersonnelEntryByStatus,
        },
        dispatch
    )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class StatisticList extends Component {
    static defaultProps = {};
    //propTypes 验证
    static propTypes = {
        actions: PropTypes.shape({
            dispatch: PropTypes.func.isRequired,
            entry: PropTypes.func.isRequired,
            dimission: PropTypes.func.isRequired,
            transferIn: PropTypes.func.isRequired,
            transferOut: PropTypes.func.isRequired,
            totalTransfer: PropTypes.func.isRequired,
            totalBeRegular: PropTypes.func.isRequired,
            entryByType: PropTypes.func.isRequired,
            entryByStatus: PropTypes.func.isRequired,
        }).isRequired
    };
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2
        });
        this.state = {
            dataSource,
            isLoading: true,
            refreshing: false,
            height: document.body.clientHeight,
            pageIndex: 0,
            hasMore: false,
            data: [],
            prePage: 1,
            pageTitle: ''
        };
    }
    componentWillMount() {
        const { change, currentDate, deptId = '', type, status, period = 'week' } = this.props.location.query || {};
        let param = {};
        if(change === 'entryByType') {
            setTitle({ title: `${typeMapper[type]}员工` });
            param = { time: currentDate, deptId: deptId, employeeType: type, page: 1, pageSize: PAGE_SIZE, periodType: period }
        } else if(change === 'entryByStatus'){
            setTitle({ title: `${statusMapper[status]}员工` });
            param = { time: currentDate, deptId: deptId, employeeStatus: status, page: 1, pageSize: PAGE_SIZE, periodType: period }
        } else {
            setTitle({ title: `${mapper[change]}员工` });
            param = { time: currentDate, deptId: deptId, page: 1, pageSize: PAGE_SIZE, periodType: period }
        }
        this.getPersonnelList(param);
        this.setState({ pageIndex: 1, param });
    }
    componentDidMount() {
        const { change, type, status } = this.props.location.query || {};
        if(change === 'entryByType') {
            setTitle({ title: `${typeMapper[type]}员工` });
        } else if(change === 'entryByStatus'){
            setTitle({ title: `${statusMapper[status]}员工` });
        } else {
            setTitle({ title: `${mapper[change]}员工` });
        }
      }
    componentWillUnmount() {  
        // this.timer && clearTimeout(this.timer);
    }
    /**
     * 获取列表数据
     * @param {*参数} param 
     */
    @autobind
    getPersonnelList(param) {
        const { change = '' } = this.props.location.query || {};
        console.log(param)
        this.props.actions[change](param)
            .then(res => {
                const { success, result } = res;
                if (success) {
                    const { list = {}, pageTitle } = result;
                    const listData = list.data || [];
                    const data = [...this.state.data, ...listData];
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(data),
                        hasMore: list.hasMore,
                        isLoading: false,
                        data,
                        param,
                        pageTitle,
                        total: list.total
                    });
                }
            });
    };

    /**
      * 滚动加载更多
      * */
    @autobind
    onEndReached() {
        if (this.state.isLoading || !this.state.hasMore) {
            return;
        }
        // if(this.state.data.length < PAGE_SIZE ){  
        //     return ;  
        // }  
        let { param } = this.state;
        const nextPage = this.state.pageIndex + 1;
        param.page = nextPage
        if (this.state.prePage !== nextPage) {
            this.state.prePage = nextPage;
            this.setState(
                {
                    isLoading: true,
                    pageIndex: nextPage,
                    prePage: nextPage,
                },
                () => {
                    this.getPersonnelList(param);
                }
            );
        }
    };

    /**
        * 顶部下拉刷新页面(use html body as a scroll container.)
        * 清零后去加载列表
        * setTimeout用于加载显示顶部刷新的loading
    * */
    @autobind
    onRefresh() {
        this.setState({ refreshing: true });
        this.state.prePage = 1;
        let { param } = this.state;
        param.page = 1;
        if(this.state.isLoading) return;
        this.timer = setTimeout(() => {
            this.setState(
                {
                    dataSource: this.state.dataSource.cloneWithRows([]),
                    refreshing: false,
                    isLoading: true,
                    pageIndex: 1,
                    hasMore: false,
                    data: [],
                    isDeleteShow: false
                },
                () => {
                    this.getPersonnelList(param);
                }
            );
        }, 1000);
    };
    @autobind
    arrowClick(userId) {
        // window.location = `?userId=${userId}#growth`;
        openLink(`?userId=${userId}#/growth`)
    }
    render() {
        const { change } = this.props.location.query || {};
        const { total, pageTitle, isLoading } = this.state;
        const row = rowData => {
            return (
                <div className="list-wrap" onClick={() => this.arrowClick(rowData.userId)}>
                    <div className="my-list">
                        <div className="avatar">
                            <DDAvatar
                                name={rowData.realName}
                                size=""
                                avatar={
                                    rowData.avatar &&
                                    mid2Url(rowData.avatar, { imageSize: "thumb" })
                                }
                                className="growth-avatar-dd-avatar"
                                font=""
                            />
                        </div>
                        <div className="contant">
                            <h4>{rowData.realName}</h4>
                            {
                                (change !== 'transferOut' ) &&
                                <p className="dept">{rowData.deptName}</p>
                            }
                            {
                                (change === 'transferOut') &&
                                <div>
                                    {
                                        rowData.toDeptName &&
                                        <div className="dept">
                                            <span className="left">转入部门：</span>
                                            <span className="right">{rowData.toDeptName}</span>
                                        </div>
                                    }
                                    {
                                        rowData.transferDate &&
                                        <div className="contant-bottom">
                                            <span className="left">入职时间：</span>
                                            <span className="right">{rowData.transferDate}</span>
                                        </div>
                                    }
                                </div>
                            }
                            {
                                ((change === 'entry' || change === 'entryByType' || change === 'entryByStatus') && rowData.hireDate) &&
                                <div className="contant-bottom">
                                    <span className="left">入职时间：</span>
                                    <span className="right">{rowData.hireDate}</span>
                                </div>
                            }
                            {
                                (change === 'dimission') &&
                                <div className="contant-bottom">
                                    {
                                        rowData.dismissionReason &&
                                        <p>
                                            <span className="left">离职原因：</span>
                                            <span className="right">{rowData.dismissionReason}</span>
                                        </p>
                                    }
                                    {
                                        rowData.deleteDate &&
                                        <p>
                                            <span className="left">离职删除日期：</span>
                                            <span className="right">{rowData.deleteDate}</span>
                                        </p>
                                    }
                                </div>
                            }
                            {
                                (change === 'transferIn') &&
                                <div className="contant-bottom">
                                    {
                                        rowData.fromDeptName &&
                                        <p>
                                            <span className="left">来自：</span>
                                            <span className="right">{rowData.fromDeptName}</span>
                                        </p>
                                    }
                                    {
                                        rowData.transferDate &&
                                        <p>
                                            <span className="left">调动日期：</span>
                                            <span className="right">{rowData.transferDate}</span>
                                        </p>
                                    }
                                </div>
                            }
                        </div>
                        
                        <div className="arrow" >
                            <Icon type="right" />
                        </div>
                    </div>
                </div>
            );
        };
        return (
            <div className="statistic-list">
                {
                    this.state.data.length !== 0 ? 
                    <ListView
                        ref={el => (this.lv = el)}
                        dataSource={this.state.dataSource}
                        initialListSize={15}
                        renderRow={row}
                        pageSize={15}
                        style={{
                            height: this.state.height
                        }}
                        scrollerOptions={{ scrollbars: true }}
                        refreshControl={
                            <RefreshControl
                                refreshing={this.state.refreshing}
                                onRefresh={this.onRefresh}
                            />
                        }
                        scrollRenderAheadDistance={500}
                        scrollEventThrottle={200}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={10}
                        renderHeader={()=>{ 
                            if (pageTitle && total !== 0) {
                                return (
                                    <div className="statistic-title">
                                        {pageTitle + total}人
                                    </div>
                                )
                            }
                        }}
                    /> : 
                    <div className="no-data">
                        {
                            !isLoading ?
                            <p>当前暂无数据</p> :
                            null
                        }
                        
                    </div>
                }
                
            </div>
        )
    }
}
